<template>
	<view class="">
		<commonHeader :showBack="true" :navigationBarStyle="{ iconText: '确认订单' }"></commonHeader>
		<view class="page-content" :style="{'padding-top': lineHeight + 'rpx'}">
			<!-- 无地址情况 -->
			<view class="create-address justify-between align-center" v-if="!address" @click="setAddress">
				<view class="icon">
					<img src="/static/icon/shopCar/icon-dizhi@2x.png" alt="" srcset="">
				</view>
				<view class="tips">新建收货地址</view>
				<u-icon name="arrow-right" color="#000000" size="16"></u-icon>
			</view>
			<!-- 有地址情况 -->
			<view class="select-address align-center" v-if="address">
				<view class="icon">
					<img src="/static/icon/shopCar/icon-dizhi@2x.png" alt="" srcset="">
				</view>
				<view class="tips name">
					<view class="">
						<span>{{ address.receiveName }}</span>
						<span>{{ address.receivePhone }}</span>
					</view>
					<view class="address-detail">
						{{ address.address }}
					</view>
				</view>
				<u-icon name="arrow-right" color="#000000" size="16"></u-icon>
			</view>
			<view class="shopbody">
				<view class="tag-title">
					商品信息
				</view>
				<view class="" v-for="(item, index) in list" :key="index">
					<view class="" v-for="(sku, subIndex) in item.skus" :key="subIndex">
						<view class="gitem">
							<view class="left">
								<image class="img" referrerpolicy="no-referrer" :src="sku.image" />
							</view>
							<view class="right">
								<view class="name line-1">
									{{ sku.productName }}
								</view>
								<view class="spac"></view>
								<view class="ops align-center">
									<view class="space-title">
										规格
									</view>
									<view class="space-content">
										{{ sku.value }}
									</view>
								</view>
								<view class="price-count justify-between align-center ">
									<view class="">
										<u-number-box button-size="29" v-model="sku.number"
											@change="e => countChange(e, sku.skuId)"></u-number-box>
									</view>
									<view class="price">
										<span class="unit">￥</span>
										<span class="price">{{ sku.price }}</span>
									</view>
								</view>
							</view>
						</view>
						<u-line color="#eee"></u-line>
					</view>

				</view>
				<view class="product-total justify-end align-center">
					<view class="title">合计</view>
					<view class="price">
						<span class="unit">￥</span>
						<span class="price">{{ getSettlement.total }}</span>
					</view>
				</view>
			</view>
			<view class="hongbao justify-between" @click="showCouponRun">
				<view class="align-center">
					<span class="hongbao-icon">￥</span>
					<span class="hongbao-title">
						红包
					</span>
				</view>
				<view class="content align-center">
					<view style="color: #E86C64;font-size: 28rpx;" v-if="couponsData && couponsData.shopCouponId">
						{{couponsData.content}}
					</view>
					<view style="color: #999;font-size: 28rpx;" v-else>暂无可用红包</view>
					<u-icon name="arrow-right" color="#000" size="14"></u-icon>
				</view>
			</view>
			<view class="remark">
				<view class="tag-title">
					商品备注
				</view>
				<view class="content align-center">
					<input type="text" placeholder="给商家留言备注" v-model="remark">
				</view>
			</view>
		</view>
		<view class="total">
			<view class="total-price align-center">
				<view class="title">
					待付款
				</view>
				<view class="price">
					<span class="unit">￥</span>
					<span class="price">{{ getSettlement.total }}</span>
				</view>
			</view>
			<view class="order-button">
				<u-button shape="circle" class="button-o" color="#FDB1B4" @click="submit(4, 1)">
					<img src="/static/icon/shopCar/icon_yue@2x.png"
						style="width: 35rpx;height: 26rpx;margin-right: 14rpx;" alt="" srcset="">
					余额支付（￥0.00）
				</u-button>
				<u-button shape="circle" class="button-o" color="#FFB356" @click="submit(4, 1)">
					<img src="/static/icon/shopCar/icon_xianxiazhuanzhang@2x.png"
						style="width: 45rpx;height: 36rpx;margin-right: 8rpx;" alt="" srcset="">
					线下转账
				</u-button>
				<u-button shape="circle" class="button-o" color="#77c545" @click="submit(1, 1)">
					<!-- <img src="/static/icon/shopCar/icon_xianxiazhuanzhang@2x.png"
						style="width: 45rpx;height: 36rpx;margin-right: 8rpx;" alt="" srcset=""> -->
					微信支付
				</u-button>
			</view>
		</view>
		<order-successfully :showOrderSuccessfullyModal="showOrderSuccessfullyModal" :getSettlement="getSettlement"
			:submitData="submitData" :address="address" @showOrderSuccessfullyModal="showOrderSuccessfullyModalFn">
		</order-successfully>
		<addressModal ref="address" @update="getCurrentUserReceive"></addressModal>
		<coupons ref="sucoupons" @useCou="useCouRun" :productIds="productIds" />
	</view>
</template>

<script>
	import {
		setPay,
		setPayAssign
	} from '@/config/utils';
	import coupons from "@/components/coupons/coupons.vue"
	import orderSuccessfully from "@/components/shopCar/order-successfully.vue"
	import addressModal from "@/components/address/address.vue"
	import base from '@/config/baseUrl';
	export default {
		components: {
			coupons,
			orderSuccessfully,
			addressModal
		},
		data() {
			return {
				count: 0,
				showCoupon: false,
				showOrderSuccessfullyModal: false,
				address: undefined,
				list: [],
				productIds: [],
				getSettlement: null,
				remark: '',
				userInfo: {},
				submitData: '',
				addressShow: true,
				couponsData: {},
				orgTotal: 0,
				lineHeight: 0
			}
		},
		onShow() {
			uni.$on('getHeight', res => {
				console.log(res, 'getHeight');
				this.lineHeight = res.ktxStatusHeight + 84;
			})
			const userInfo = uni.getStorageSync('userInfo');
			if (userInfo) {
				this.userInfo = userInfo
			}
			this.getCurrentUserReceive()
			this.getAll()
			this.getCart().then((res) => {
				this.getSettlement2()
			})
			uni.connectSocket({
				url: `${base.socketUrl}payserver/${userInfo.buyerUserId}`
			});
			uni.onSocketOpen((res) => {
				console.log('WebSocket连接已打开！');
				console.log(res);
			});
			uni.onSocketError(function(res) {
				console.log('WebSocket连接打开失败，请检查！');
			});
			uni.onSocketMessage((res) => {
				console.log('收到服务器内容：' + res.data);
				console.log(res.data);
				let payres = {}
				try {
					payres = JSON.parse(res.data)
				} catch (e) {
					console.error('json格式化错误，不必理会');
					console.error(e);
				}
				if (payres.code == 200) {
					console.log('1')
					this.showOrderSuccessfullyModal = true
				} else {
					uni.showToast({
						title: payres.msg,
						icon: 'none',
						duration: 1000,
					})
				}
			});
		},
		onUnload() {
			uni.onSocketClose(function(res) {
				console.log('WebSocket 已关闭！');
			});
		},
		methods: {
			setAddress() {
				this.$nextTick(() => {
					console.log(this.$refs.address.addressShow);
					this.$refs.address.addressShow = true
					this.$refs.address.firstAdd = true

				})
			},
			showCouponRun() {
				this.$refs.sucoupons.open(this.productIds)
			},
			// 提交订单
			// paymentMode 1微信 2支付宝 3花呗 4线下
			// subPaymentMode 1微信 2支付宝 3h5支付
			submit(paymentMode, subPaymentMode) {
				if (!this.address) {
					uni.showToast({
						title: '收货地址未设置，请设置',
						icon: 'none',
						duration: 1000,
					})
					return
				}
				const param = {
					paymentMode: paymentMode,
					subPaymentMode: paymentMode,
					price: this.getSettlement.total,
					receiveId: this.address.receiveId, // 收货地址id	
					remark: this.remark, // 订单备注
					shopCouponIds: this.couponsData.shopCouponId ? [this.couponsData.shopCouponId] : [],
					shops: []
				}
				this.list.forEach((item, index) => {
					param.shops.push({
						id: this.couponsData.shopCouponId ? this.couponsData.shopCouponId: '',
						shopId: item.shopId,
						skus: []
					})
					item.skus.forEach((subItem, subIndex) => {
						param.shops[index].skus.push({
							ifLogistics: subItem.ifLogistics,
							number: subItem.number,
							selected: subItem.selected,
							skuId: subItem.skuId,
							selected: 1
						})
					})
				})
				console.log(param);
				this.$http.post("order/submit", param).then(res => {
					this.submitData = res
					if (paymentMode == 1) {
						// 小程序
						const payData = res.payInfo
						console.log(payData);
						payData.provider = "wxpay"
						uni.requestPayment({
							provider: "wxpay",
							appId: payData.appId,
							nonceStr: payData.nonceStr,
							out_trade_no: payData.out_trade_no,
							package: payData.package,
							paySign: payData.paySign,
							prepayId: payData.prepayId,
							signType: payData.signType,
							timeStamp: payData.timeStamp,
							success(res) {
								console.log(res);
							},
							fail(e) {
								console.error(e);
							}
						})
						return
					}
					this.showOrderSuccessfullyModal = true
					console.log(res, 'submit');
				}).catch(res => {
					console.log(res, 1234);
				})
			},
			getCurrentUserReceive() {
				this.$http.get("receive/getCurrentUserReceive", {}).then(res => {
					this.address = res
					console.log(this.address, '123');
				}).catch(res => {
					console.log(res, 1234);
				})
			},
			getAll() {
				this.$http.get("receive/getAll", {
					page: 1,
					pageSize: 10
				}).then(res => {
					console.log(res);
				}).catch(res => {
					console.log(res, 1234);
				})
			},
			// 购物车列表
			async getCart() {
				const shopInfo = uni.getStorageSync('shopInfo');
				await this.$http.get("cart/getCart", {
					shopId: shopInfo.shopId
				}).then(res => {
					this.list = res
					const temp = []
					for (const some of this.list) {
						for (const sku of some.skus) {
							temp.push(sku.productId)
						}
					}
					const setArr = new Set(temp)
					this.productIds = [...setArr]
					console.log(this.productIds);
				})
			},
			// 购物车总计
			getSettlement2() {
				const param = {
					shops: [
						// 	{
						// 	shopId: 187,
						// 	skus: [{
						// 		ifLogistics: 1,
						// 		number: 3,
						// 		selected: 1,
						// 		skuId: 1
						// 	}]
						// },
					]
				}
				this.list.forEach((item, index) => {
					param.shops.push({
						shopId: item.shopId,
						skus: []
					})
					item.skus.forEach((subItem, subIndex) => {
						param.shops[index].skus.push({
							ifLogistics: subItem.ifLogistics,
							number: subItem.number,
							selected: subItem.selected,
							skuId: subItem.skuId
						})
					})
				})
				this.$http.post("order/getSettlement2", param).then(res => {
					res.total = 0
					res.number = 0
					res.shops.forEach((item, index) => {
						res.total = res.total + item.total
						res.number = res.number + item.number
					})
					res.total = res.total.toFixed(2)
					this.orgTotal = res.total
					this.getSettlement = res
				})
			},

			couponChange() {},
			countChange(v, skuId) {
				console.log(v, skuId);
				this.updateNumber(v.value, skuId).then(res => {
					this.getSettlement2()
				})
			},
			async updateNumber(number, skuId) {
				const param = {
					number: number,
					skuId: skuId
				}
				await this.$http.post("cart/updateNumber", param).then(res => {})
			},
			showCouponFn(value) {
				this.showCoupon = value
			},
			showOrderSuccessfullyModalFn(value) {
				this.showOrderSuccessfullyModal = value
				let pages = getCurrentPages()

				// 2. 上一页面实例
				// 注意是length长度，所以要想得到上一页面的实例需要 -2
				// 若要返回上上页面的实例就 -3，以此类推
				let prevPage = pages[pages.length - 2]
				prevPage.$vm.popRefreshData()
				uni.navigateBack({})
			},
			useCouRun(e) { // e为null则不使用红包
				console.log(e);
				this.couponsData = e
				if (e.reduceMoney) {
					this.getSettlement.total = this.orgTotal - this.couponsData.reduceMoney
					this.getSettlement.total.toFixed(2)
				} else {
					this.getSettlement.total = this.orgTotal
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.page-content {
		// padding-bottom: 380rpx;
		padding-bottom: calc(env(safe-area-inset-bottom) + 380rpx);
		padding-bottom: calc(constant(safe-area-inset-bottom) + 380rpx);
	}

	.create-address {
		padding: 30rpx 35rpx 60rpx;
		background: #fff;
		border-bottom: 6rpx dashed #E66E63;

		.icon img {
			height: 43rpx;
			width: 38rpx;
		}

		.tips {
			color: #999;
			font-size: 32rpx;

			.address-detail {
				font-size: 34rpx;
				font-weight: 600;
				color: #333333;
			}
		}

	}

	.select-address {
		padding: 30rpx 35rpx 30rpx;
		background: #fff;
		border-bottom: 6rpx dashed #E66E63;

		.icon img {
			height: 43rpx;
			width: 38rpx;
		}

		.tips {
			color: #999;
			font-size: 32rpx;

			.address-detail {
				font-size: 34rpx;
				font-weight: 600;
				color: #333333;
			}
		}

		.name {
			padding-left: 40rpx;
			flex: 1;

			view:first-child {
				margin-bottom: 10rpx;
			}
		}

	}

	.shopbody {
		width: 700rpx;
		margin: 25rpx;
		box-sizing: border-box;
		border-radius: 12rpx;
		box-shadow: 0px 2rpx 24rpx 0px rgba(51, 51, 51, 0.1200);
		background: #FFFFFF;

		.tag-title {
			position: relative;
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 25rpx 0 46rpx;
			font-size: 32rpx;
			color: #333;
			border-bottom: 1px solid #eee;
			margin-bottom: 15rpx;
		}

		.tag-title::before {
			position: absolute;
			top: 50%;
			left: 25rpx;
			width: 8rpx;
			height: 30rpx;
			line-height: 30rpx;
			background-color: #FA625D;
			transform: translateY(-50%);
			content: "";
			border-radius: 4rpx;
		}

		.gitem {
			width: 100%;
			height: 215rpx;
			padding: 20rpx 25rpx;
			display: flex;
			background: #fff;

			.left {
				width: 205rpx;
				height: 100%;

				.img {
					width: 205rpx;
					height: 140rpx;
					box-shadow: 0px 2px 24px 0px rgba(51, 51, 51, 0.12);
					border-radius: 8rpx;
				}
			}

			.right {
				flex: 1;
				height: 100%;
				padding-left: 20rpx;

				.name {
					width: 136rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					font-weight: 600;
					color: #333333;
					line-height: 39rpx;
					padding-bottom: 16rpx;
				}

				.ops {
					.space-title {
						width: 88rpx;
						font-size: 26rpx;
						font-weight: 400;
						color: #fff;
						background: #FA625D;
						border-radius: 4rpx;
						text-align: center;
					}

					.space-content {
						height: 45rpx;
						line-height: 45rpx;
						font-size: 26rpx;
						border-radius: 4rpx;
						font-weight: 400;
						color: #333333;
						margin-left: 20rpx;
					}
				}

				.price-count {
					margin-top: 10rpx;

					.price {
						.unit {
							font-size: 28rpx;
							font-family: SF UI Text;
							font-weight: 400;
							color: #333;
							line-height: 48rpx;
							height: 28px;
						}

						.price {
							font-size: 40rpx;
							font-family: SF UI Text;
							font-weight: bold;
							color: #333;
							line-height: 48rpx;
							height: 28px;
						}
					}

					.u-number-box,
					.u-number-box__minus,
					.u-number-box__plus {
						height: 58rpx !important;
					}
				}
			}
		}

		.product-total {
			height: 80rpx;
			line-height: 80rpx;

			.title {
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #666666;
			}

			.price {
				padding-right: 10rpx;
				padding-left: 10rpx;

				.unit {
					font-size: 28rpx;
					font-family: SF UI Text;
					font-weight: 400;
					color: #E86C64;
					line-height: 48rpx;
					height: 28px;
				}

				.price {
					font-size: 40rpx;
					font-family: SF UI Text;
					font-weight: bold;
					color: #E86C64;
					line-height: 48rpx;
					height: 28px;
				}
			}
		}
	}

	.hongbao {
		width: 700rpx;
		height: 88rpx;
		line-height: 88rpx;
		margin: 25rpx;
		box-sizing: border-box;
		border-radius: 12rpx;
		box-shadow: 0px 2rpx 24rpx 0px rgba(51, 51, 51, 0.1200);
		background: #FFFFFF;
		padding-left: 25rpx;
		padding-right: 25rpx;

		&-icon {
			display: inline-block;
			width: 36rpx;
			height: 36rpx;
			background: #E66E63;
			border-radius: 6rpx;
			font-size: 28rpx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #FFFFFF;
			line-height: 39rpx;
			text-align: center;
		}

		&-title {
			padding-left: 13rpx;
		}
	}

	.remark {
		width: 700rpx;
		margin: 25rpx;
		box-sizing: border-box;
		border-radius: 12rpx;
		box-shadow: 0px 2rpx 24rpx 0px rgba(51, 51, 51, 0.1200);
		background: #FFFFFF;

		.tag-title {
			position: relative;
			height: 80rpx;
			line-height: 80rpx;
			padding: 0 25rpx 0 46rpx;
			font-size: 32rpx;
			color: #333;
			border-bottom: 1px solid #eee;
		}

		.tag-title::before {
			position: absolute;
			top: 50%;
			left: 25rpx;
			width: 8rpx;
			height: 30rpx;
			line-height: 30rpx;
			background-color: #FA625D;
			transform: translateY(-50%);
			content: "";
			border-radius: 4rpx;
		}

		.content {
			padding: 25rpx;

			input {
				font-size: 28rpx;
			}
		}
	}

	.total {
		position: fixed;
		bottom: 0rpx;
		// height: 280rpx;
		width: 100%;
		background: #FFFFFF;
		box-shadow: 0px 1rpx 8rpx 0px rgba(153, 153, 153, 0.1200);
		z-index: 999;

		.total-price {
			flex: 1;
			padding: 19rpx 25rpx;
			border-bottom: 2rpx solid #eee;

			.title {
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #666666;
			}

			.price {
				.unit {
					font-size: 28rpx;
					font-family: SF UI Text;
					font-weight: bold;
					color: #E86C64;
					height: 28px;
					padding: 0 0 0 15rpx;
				}

				.price {
					font-size: 36rpx;
					font-family: SF UI Text;
					font-weight: bold;
					color: #E86C64;
				}
			}
		}

		.order-button {
			width: 720rpx;
			margin: 0 auto;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);

			/deep/.u-button {
				height: 75rpx !important;
				margin-top: 12rpx !important;
				margin-bottom: 14rpx !important;
			}

			.button-o {
				height: 75rpx !important;
				margin-top: 14rpx !important;
			}
		}
	}

	/deep/ .u-number-box__input {
		width: 100rpx !important;
	}
</style>
